

from flask import render_template, g, request, redirect, jsonify, current_app

from info import db, constants
from info.lib.Decorator.Decorator_init import user_login
from info.models import Category,News

from info.modules.profile import profile_blu
from info.utlis.image_storage import storage
from info.utlis.response_code import RET


@profile_blu.route('/news_list',methods=['GET'])
@user_login
def news_list():
    """
    1 查询该用户的发布的所有新闻
    :return:
    """
    user = g.user
    # 获取页数
    user = g.user
    # 获取页数
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    paginate = []
    current_page = 1
    total_page = 1

    # 查询该用户发布的所有新闻
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p ,constants.USER_COLLECTION_MAX_NEWS,False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据库查询失败')

    collections_list = []
    # 获取所有信息数据
    for news in collections:
        collections_list.append(news.to_basic_dict())

    date = {
        'total_page': total_page,
        'current_page': current_page,
        'collections_list': collections_list
    }
    return render_template('news/user_news_list.html', date=date)

@profile_blu.route('/news_release',methods=['POST','GET'])
@user_login
def news_release():
    """
    1 获取数据
    2 校验数据
    3 修改数据
       1 查询所有分类数据
       2 将数据返回
     返回响应
    :return:
    """
    categories = []
    # 取出所有分类数据
    if request.method == 'GET':
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.debug(e)

        categories_list = []
        for categorie in categories:
            categories_list.append(categorie.to_dict())

        categories_list.pop(0)

        date={
            'categories':categories_list
        }

        return render_template('news/user_news_release.html',date=date)



    user = g.user
    # 获取数据
    title = request.form.get('title')# 标题
    digest = request.form.get('digest')# 摘要
    source = '个人发布'
    category_id = request.form.get('category_id')# 新闻分类
    content = request.form.get('content')# 内容


    # 判断是否有数据
    if not all([title,digest,content]):
        return jsonify(errno=RET.NODATA, errmsg='无数据')

    # 获取图片信息
    try:
        index_image = request.files.get('index_image').read()
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据错误')

    # 上传到七牛云
    try:
        url = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

    # 初始化新闻数据
    news = News()
    news.title = title
    news.source = source
    news.digest = digest
    news.content = content
    news.index_image_url = url
    news.category_id = category_id
    news.user_id = user.id

    # 设置为待审核状态


    # 添加新闻
    db.session.add(news)
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.debug(e)
        db.session.rollback()# 操作回滚



    return jsonify(errno=RET.OK, errmsg='发布成功')




@profile_blu.route('/collection')
@user_login
def user_collection():
    """
    1 获取用户信息
    2 查询其收藏的新闻
    3 返回参数
    :return:
    """
    user = g.user
    # 获取页数
    p = request.args.get('p',1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.debug(e)
        return jsonify(errno=RET.DATAERR, errmsg='参数错误')
    collections = []
    current_page = 1
    total_page = 1

    # 查询该用户收藏的新闻
    try:
        paginate = user.collection_news.paginate(p ,constants.USER_COLLECTION_MAX_NEWS,False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)

    collections_list =[]
    # 获取所有信息数据
    for news in collections:
        collections_list.append(news.to_basic_dict())

    date={
        'total_page':total_page,
        'current_page':current_page,
        'collections_list':collections_list
    }

    return render_template('news/user_collection.html', date=date)

@profile_blu.route('/pass_info', methods=["GET", "POST"])
@user_login
def pass_info():
    """
    修改密码需要
    1 判断请求类型
    2 获取参数
    3 校验参数
    4 修改数据库
    5 返回数据
    :return:
    """

    user = g.user

    # 如果请求为GET，则刷新
    if request.method == 'GET':
        date = {
            'user_id': user.to_dict()
        }

        return render_template('news/user_pass_info.html', date=date)
    if request.method == 'POST':
        # 获取参数
        old_password = request.json.get('old_password')
        new_password = request.json.get('new_password')

        # 判断是否为空
        if not all(['old_password','new_password']):
            return jsonify(errno=RET.DATAEXIST, errmsg='无数据')

        # 校验原密码
        if not user.check_password(old_password):
            return jsonify(errno=RET.PWDERR, errmsg="原密码错误")

        # 转换成整形


        # 修改数据
        user.password = new_password

        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.debug(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

        return jsonify(errno=RET.OK, errmsg='OK')



    return render_template('news/user_pass_info.html')


@profile_blu.route('/pic_info', methods=['POST', 'GET'])
@user_login
def pic_info():
    """
    1 判断请求类型
    2 接受文件参数
    3 调用第三方库
    :return:
    """
    user = g.user

    # 如果没有传参数
    if request.method == 'GET':
        date ={
            'user_id': user.to_dict()
        }
        return render_template('news/user_pic_info.html' ,date=date)

    if request.method == "POST":

    # 获取图片文件
        try:
            avatar_file = request.files.get("avatar").read()
        except Exception as e:
            current_app.logger.debug(e)
            return jsonify(errno=RET.DATAERR, errmsg='图片读取失败')

        # 上传到七牛云
        try:
            url = storage(avatar_file)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")

        # 将图片地址添加到数据库
        user.avatar_url = url

        # 提交
        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.debug(e)

        date={
            'avatar_url': constants.QINIU_DOMIN_PREFIX + url

        }

        return jsonify(errno=RET.OK, errmsg='上传成功', date=date)






@profile_blu.route('/base_info', methods=['POST' ,'GET'])
@user_login
def base_info():
    """
    1 判断请求方式
    2 获取参数 （nick_name）
    3 校验参数
    4 修改数据
    5 返回响应
    :return:
    """
    user = g.user



    # 如果没有传参数
    if request.method == 'GET':
        date ={
            'user_id': user.to_dict()
        }
        return render_template('news/user_base_info.html' ,date=date)

    # 如果传递参数
    if request.method == "POST":
        # 获取参数
        nick_name = request.json.get('nick_name')
        signature = request.json.get('signature')
        gender = request.json.get('gender')

        # 参数是否为空
        if not all([nick_name,signature,gender]):
            return jsonify(errno=RET.DATAEXIST, errmsg='无数据')
        # 性别参数是否合理
        if gender not in ('MAN', 'WOMAN'):
            return jsonify(errno=RET.NODATA, errmsg='数据错误')
        # 初始化
        user.nick_name = nick_name
        user.gender = gender
        user.signature = signature
        # 添加数据
        db.session.add(user)
        # 提交到数据库
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.debug(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg='数据库查询错误')

        return jsonify(errno=RET.OK, errmsg='修改成功')

    return render_template('news/user_base_info.html')


@profile_blu.route('/user')
@user_login
def profile():

    user = g.user
    # 用户是否已经登陆
    if not user:
        return redirect('/')

    date={
        'user_id': user.to_dict() if user else None
    }
    return render_template('news/user.html', date=date)
